package com.dy.yunying.biz.controller.datacenter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import com.dy.yunying.api.constant.Constant;
import com.dy.yunying.api.datacenter.export.AdExportDataAnalysisVO;
import com.dy.yunying.api.datacenter.export.AdExportDataVo;
import com.dy.yunying.api.datacenter.export.MaterialExportDataDTO;
import com.dy.yunying.api.dto.MaterialDataDTO;
import com.dy.yunying.api.vo.MaterialDataVO;
import com.dy.yunying.biz.service.datacenter.MaterialDataService;
import com.dy.yunying.biz.utils.DateUtils;
import com.dy.yunying.biz.utils.ExportAlibabaUtils;
import com.dy.yunying.biz.utils.ExportUtils;
import com.dy.yunying.biz.utils.MapUtils;
import com.pig4cloud.pig.common.core.exception.BusinessException;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 素材数据报表Controller
 */

/**
 * 广告数据分析表相关接口
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/dataCenter/materialData")
public class MaterialDataController {

	private static final String[] PERCENT_KEYS = {"materialUsageRate", "play10perRate", "play25perRate", "play50perRate", "play75perRate", "play95perRate", "play99perRate", "playOverRate", "playValidRate", "showClickRate", "clickActiveRate", "clickRegisterRate", "newPayRetention2", "newPayRate", "totalRoi", "firstRoi", "retention2", "retention7", "retention30"};

	private final MaterialDataService materialDataService;

	/**
	 * 获取素材数据报表总数
	 *
	 * @param material
	 * @return
	 */
	@PostMapping("/count")
	public R<Map<String, Object>> count(@RequestBody MaterialDataVO material) {
		final Integer count = materialDataService.count(material);
		return R.ok(Collections.singletonMap("total", count));
	}

	/**
	 * 获取素材数据报表分页列表
	 *
	 * @param material
	 * @return
	 */
	@PostMapping("/list")
	public R<Map<String, Object>> list(@RequestBody MaterialDataVO material) {
		final List<MaterialDataDTO> list = materialDataService.list(material, Boolean.TRUE);
		return R.ok(Collections.singletonMap("list", list));
	}

	/**
	 * 素材管理-数据
	 * @param material
	 * @return
	 */
	@PostMapping("/materialData")
	public R materialData(@RequestBody MaterialDataVO material){
		if (StringUtils.isBlank(material.getSdate()) || StringUtils.isBlank(material.getEdate())){
			return R.failed("请选择开始时间和结束时间");
		}
		if (null == material.getDataType()){
			return R.failed("数据类型不能为空");
		}
		return materialDataService.materialData(material);
	}

	/**
	 * 素材数据报表导出
	 *
	 * @param material
	 * @param request
	 * @param response
	 */
	@ResponseExcel(name = "素材数据报表导出", sheet = "素材数据报表导出")
	@GetMapping("/export")
	public void export(@Valid MaterialDataVO material, HttpServletRequest request, HttpServletResponse response) {
		try {
			String sheetName = "素材数据报表";
			List<MaterialDataDTO> resultList = materialDataService.list(material, Boolean.FALSE);
			resultList.addAll(materialDataService.list(material.setPeriod(4).setGroupBys(Collections.emptyList()), Boolean.FALSE));


			String fileName = URLEncoder.encode("素材数据报表-"+ DateUtils.getCurrentTimeNoUnderline(), "UTF-8").replaceAll("\\+", "%20");

			List<Map<String, Object>> resultListMap = MapUtils.objectsToMaps(resultList);

			ExportUtils.spliceSuffix(resultListMap, Constant.PERCENT, Constant.DEFAULT_VALUE,PERCENT_KEYS);

			List<MaterialExportDataDTO> list= new ArrayList<>();

			JSONArray array = JSONArray.parseArray(JSON.toJSONString(resultListMap));

			for (int i = 0; i < array.size(); i++) {
				JSONObject jsonObject = array.getJSONObject(i);
				MaterialExportDataDTO detail = JSON.parseObject(String.valueOf(jsonObject), MaterialExportDataDTO.class);
				list.add(detail);
			}

			ExportAlibabaUtils.exportExcelData(response,sheetName,fileName,material.getColumns(),list,MaterialExportDataDTO.class);

		} catch (BusinessException e) {
			log.error("exportMaterialData is error", e);
			throw e;
		} catch (Exception e) {
			log.error("exportMaterialData is error", e);
			throw new BusinessException("导出异常");
		}
	}

}
